function MainAssistant(argFromPusher) {
}

// only for development testing purpose
var showDuplicates = false; 

// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// declare global variables and define their defaults
this.needRefresh = false;
var gotGPSfix = false; 
var myMinDate ={}; 
var interval; 
var myLastUpdated = new Date(); 
this.setMinDate('1d');
var myPeriod = "D"; 
var mySort1 = "datetime";
var mySort2 = true;
var nbOfItems = 0;
var myNewItems = [];
var myIndex = [];
var maxRecords = 500;

// open SQLite databses
var db = new Mojo.Depot({name:"dbLastData", version:1, replace:false},
			function(){}, 
			function(err){ Mojo.Log.error("Open dbLastData NotOK", err.message);}
);

// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
MainAssistant.prototype = {
	
	setup: function() {
					// myInfo("SETUP: Start function");
		this.currPrefs = { 
			lat: 0.0,
			lon: 0.0,
			mag: 3.0,
			dst: "K",
			maxDist: 20037.0,
			palmDark: false,
			period: "W",
			pageRefresh: 10,
			gotGPSfix: false,
			triedGPSalready: false,
			tecPlates: false,
			EMSC: true,
			USGS: true
		};
		Ares.setupSceneAssistant(this);
					// myInfo("SETUP: Ares.setupSceneAssistant(this) done");
		// define Application Menu ~~~~~~~~~~~~~~~~~~~~~~~~
		this.controller.setupWidget(Mojo.Menu.appMenu,
			this.attributes = {
				omitDefaultItems: true
			},
			this.model = {
				visible: true,
				items: [ 
					Mojo.Menu.editItem,
					{ label: $L("Preferences"), command: 'do-myPrefs' },
					// { label: $L("Help"), command: 'do-myHelp' },
					// { label: $L("Delete Cookie"), command: 'do-reset'},
					{ label: $L("About SeismiX"), command: 'do-myAbout'}
				]
			}
		);
		
		// define Command Menu ~~~~~~~~~~~~~~~~~~~~~~~~
		this.cmdMenuModel = {
			items: [ 
				{label: $L('Refresh'), icon: "sync", command: "do-Refresh"},
				{label: 'X', items : [
					{label: $L('Sort by'), submenu:'_sortMenu'},
					{label: $L('Period'), submenu:'_periodMenu'}
					]
				},
				{label: $L('Prefs'), iconPath: "images/gear32x32_1.png", command: "do-myPrefs"}
			]
		};
		this._sortMenuModel = {
			toggleCmd:'back',
			items: [
				{label: $L('Date/Time'), command:'do-sort-dat'}, 
				{label: $L('Distance'), command:'do-sort-dist'}, 
				{label: $L('Magnitude'), command:'do-sort-mag'}, 
				{label: $L('Region'), command:'do-sort-reg'}, 
				{label: $L('Depth'), command:'do-sort-dep'} 
			]
		};
		this._periodMenuModel = {
			items: [
				{label: $L('1 day'), command:'do-1d'},
				{label: $L('1 week'), command:'do-1w'}
			]
		};
		this.controller.setupWidget(Mojo.Menu.commandMenu, undefined, this.cmdMenuModel);
		this.controller.setupWidget('_sortMenu', undefined, this._sortMenuModel);
		this.controller.setupWidget('_periodMenu', undefined, this._periodMenuModel);
		this.needRefresh = true;
					// myInfo("SETUP: End function");
	}, //end setup: function
	
	activate: function(args){
					// myInfo("ACTIVATE: Start function");
		this.switchSpinnerUSGS("off");
		this.switchSpinnerEMSC("off");
					// myInfo("ACTIVATE:Before start getCurrentPosition()");
					// try to get a quick location fix or get the position from myLocation-settings
		this.$.gps.getCurrentPosition();
					// myInfo("ACTIVATE:After start getCurrentPosition()");
		if (this.needRefresh === true) {
					// myInfo("ACTIVATE: needRefresh = true");
					// myInfo("SETUP:Before start getPreferences()");
			this.getPrefs();
					// myInfo("SETUP:After start getPreferences()");
			if (this.currPrefs.palmDark == true) {
				this.controller.document.body.addClassName('palm-dark');
			}
			else {
				if (this.controller.document.body.hasClassName('palm-dark')) {
					this.controller.document.body.removeClassName('palm-dark');
				}
			}
			window.clearInterval(interval);
			interval = window.setInterval(this.getEQdata.bind(this), (this.currPrefs.pageRefresh * 60 * 1000));
			var x = [{flynn_region : $L("Contacting web service...")}];
			this.lstEQModel.items = x;
			this.controller.modelChanged(this.lstEQModel);
			this.getEQdata();
			this.needRefresh = false;
		}
					// myInfo("ACTIVATE: End function");
	},
	
	cleanup: function() {
		Ares.cleanupSceneAssistant(this);
	},
	
	handleCommand: function(event) {
		if (event.type === Mojo.Event.command) {
			if (event.command == 'do-Refresh') { 
					this.getEQdata();
			}
			if (event.command == "do-myPrefs") {
				this.controller.stageController.pushScene("scnPrefs");
			}
			if (event.command == "do-myAbout") {
				this.controller.stageController.pushScene("scnAbout");
			}
			if (event.command == 'do-KillCookie') { 
				try {
					var PrefsCookie = new Mojo.Model.Cookie('PrefsCookie');
					PrefsCookie.remove();
					Mojo.Controller.getAppController().showBanner({messageText: $L("Cookie deleted."), icon: "images/day-event-info-press.png"},{source: 'notification'});
				}
				catch(err) {
					Mojo.Controller.errorDialog("Could not delete cookie.");
				}
			}
			if (event.command == "do-myHelp") {
			}
			if (event.command == 'do-1d') {
				myPeriod = "D";
				setMinDate("1d");
				this.getEQdata();
			}
			if (event.command == 'do-1w') {
				myPeriod = "W";
				setMinDate("1w");
				this.getEQdata();
			}
			if (event.command == 'do-1m') {
				myPeriod = "M";
				setMinDate("1m");
				this.getEQdata();
			}
			if (event.command == 'do-sort-dat') {
				mySort1 = "datetime";
				mySort2 = true;
				this.lstEQModel.items.sort(sort_by("datetime", true));
				this.controller.modelChanged(this.lstEQModel);
			}
			if (event.command == 'do-sort-dist') {
				mySort1 = "dist";
				mySort2 = false;
				this.lstEQModel.items.sort(sort_by("dist", false, parseInt));
				this.controller.modelChanged(this.lstEQModel);
			}
			if (event.command == 'do-sort-mag') {
				mySort1 = "mag";
				mySort2 = true;
				this.lstEQModel.items.sort(sort_by("mag", true, parseFloat));
				this.controller.modelChanged(this.lstEQModel);
			}
			if (event.command == 'do-sort-reg') {
				mySort1 = "flynn_region";
				mySort2 = false;
				this.lstEQModel.items.sort(sort_by("flynn_region", false));
				this.controller.modelChanged(this.lstEQModel);
			}
			if (event.command == 'do-sort-dep') {
				mySort1 = "dep";
				mySort2 = false;
				this.lstEQModel.items.sort(sort_by("depth", false, parseFloat));
				this.controller.modelChanged(this.lstEQModel);
			}
		}
	},
	
	getPrefs: function() {
					// myInfo("GETPREFS: Start function");
		var prefsCookie = new Mojo.Model.Cookie('PrefsCookie');
		var prefsData;
		try {
			prefsData = prefsCookie.get();
		}
		catch(err) {
			Mojo.Controller.errorDialog($L("Could not read the cookie storing the preferences."));
		}
		if (prefsData !== undefined) { 
			// if no GPS fix available, take the coordinates from preferences, otherwise don't touch them, as set by the GPS fix
			if (this.currPrefs.gotGPSfix == false) {
				this.currPrefs.lat = prefsData.myLat;
				this.currPrefs.lon = prefsData.myLon;
			}
			this.currPrefs.mag = prefsData.myMag;
			this.currPrefs.dst = prefsData.myDist;
			this.currPrefs.maxDist = prefsData.myMaxDist;
/*			this.currPrefs.showInfo = prefsData.myShowInfo;
			this.currPrefs.Info = prefsData.myInfo;
			// to cater for update from 2.0.0 to 2.1.0, when myInfo was introduced
			if (prefsData.myShowInfo == 1 || prefsData.myInfo == undefined){
				this.currPrefs.Info = "H";
			}
			else if (prefsData.myShowInfo == 0) {
				this.currPrefs.Info = "N";
			}
*/		this.currPrefs.palmDark = prefsData.myPalmDark;
			this.currPrefs.pageRefresh = prefsData.myPageRefresh;
			this.currPrefs.override = prefsData.myOverride;
			this.currPrefs.EMSC = prefsData.myEMSC;
			this.currPrefs.USGS = prefsData.myUSGS;
			this.currPrefs.tecPlates = prefsData.myTecPlates;
		}
					// myInfo("GETPREFS: End function");
	},
	
	getWSdata: function(){
						// myInfo("GETWSDATA: Start function");
		myNewItems = [];
		myIndex = [];
		nbOfItems = 0;
		// ESMC WS **************************************************************
		if (this.currPrefs.EMSC == true || this.currPrefs.EMSC == undefined) {
			if (this.$.wsEMSC.isReady()){
							// myInfo("GETWSDATA: SeismicPortal isReady = true");
				this.getPrefs();
				var params = {};
				params.limit=maxRecords;
				params.format="json";
				params.sort="datetime";
				params.dir="DESC";
				params.magMin = this.currPrefs.mag;
				if (myMinDate.value) {params.dateMin=myMinDate.value;}
				this.$.wsEMSC.setParameters(params);
				this.switchSpinnerEMSC("on");
				this.$.wsEMSC.execute();
			}
			else {
						// myInfo("GETWSDATA: SeismicPortal isReady = false");
				this.wsEMSCCancel();
			}
		}
		// USGS WS **************************************************************
		if (this.currPrefs.USGS == true || this.currPrefs.USGS == undefined) {
			if (this.$.wsUSGS.isReady()){
							// myInfo("GETWSDATA: USGS isReady = true");
				if (myPeriod == 'D'){
							// myInfo("GETWSDATA: 1 day");
					if (this.currPrefs.mag < 2.5) {
						this.$.wsUSGS.url = "http://earthquake.usgs.gov/earthquakes/catalogs/eqs1day-M1.txt";
					}
					else {
						this.$.wsUSGS.url = "http://earthquake.usgs.gov/earthquakes/catalogs/eqs1day-M2.5.txt";
					}
				}
				else {
							// myInfo("GETWSDATA: 7 days ");
					// initially used http://earthquake.usgs.gov/earthquakes/catalogs/eqs7day-M1.txt, but then switched to +2.5 due to performance/data size reason
					if (this.currPrefs.mag < 2.5) {
						this.$.wsUSGS.url = "http://earthquake.usgs.gov/earthquakes/catalogs/eqs7day-M1.txt";
					}
					else if (this.currPrefs.mag < 5) {
						this.$.wsUSGS.url = "http://earthquake.usgs.gov/earthquakes/catalogs/eqs7day-M2.5.txt";
					}
					else if (this.currPrefs.mag < 7) {
						this.$.wsUSGS.url = "http://earthquake.usgs.gov/earthquakes/catalogs/eqs7day-M5.txt";
					}
					else {
						this.$.wsUSGS.url = "http://earthquake.usgs.gov/earthquakes/catalogs/eqs7day-M7.txt";
					}
				}
							// myInfo("GETWSDATA: ", this.$.wsUSGS.url);
				this.switchSpinnerUSGS("on");
				this.$.wsUSGS.execute();
			}
			else {
						// myInfo("GETWSDATA: USGS isReady = false");
				this.wsUSGSCancel();
			}
		}
		// No datasource selected **************************************************************
		if ((this.currPrefs.EMSC == false) && (this.currPrefs.USGS == false)) {
			this.controller.showAlertDialog({
				preventCancel: false,
				onChoose: function(value) {
					if (value == 'myPrefs') {
						var event = {
							command : "do-myPrefs",
							type : "mojo-command"
						};
						this.handleCommand(event);
					}
				},
				title: $L("Error"),
				message: $L("No data source has been selected! Please select at least one data source on the preferences screen."),
				choices:[
					{label:$L('Open Preferences'), value:"myPrefs", type:'affirmative'}
				]
			});
			this.switchSpinnerUSGS("off");
			this.switchSpinnerEMSC("off");
		}
						// myInfo("GETWSDATA: End function");
	},
	
	getEQdata: function() {
		this.getWSdata();
	},
	
	prepEQData: function(pItems, pSource) {
					// myInfo("prepEQData: Entering function", pSource);
					// Mojo.Controller.getAppController().showBanner({messageText:"Start prepEQData" + pSource, icon: "images/small-error-icon.png"},{source: 'notification'});
		var myItems = pItems;
		var nbOfItems = 0;
		var prevItems = myNewItems.length;
		var lati = this.currPrefs.lat;
		var loni = this.currPrefs.lon;
		var dsti = this.currPrefs.dst;
		var magMin = this.currPrefs.mag;
		var maxDisti = this.currPrefs.maxDist;
		var dateTimeHeader = $L("Date/Time (UTC)");
		var distHeader = $L("Distance");
		var depthHeader = $L("Depth");
		var indexStr = "";

		// Mojo.Log.info("myItems = %j", myItems);
		try {
			myItems.each(
				function(name, index){
								// myInfo("prepEQData - myItems.each: Start function - ", index);
					if (parseFloat(name.mag, 10) >= parseFloat(magMin, 10)) { // only if this EQ has a mag >= the minMag defined in the settings, continue processing of the entry
						if (!isNaN(Date.parse(name.datetime))) {
							name.datetime = ISODateString(new Date(name.datetime));
						}
						// only if this EQ isn't already present in the index 'myIndex' of the resulting array, calc dist and add it to result set
						indexStr = name.datetime.substring(0,17) + Math.ceil(parseFloat(name.mag, 10));
						// myInfo("Search for:", indexStr);
						if ((myIndex.toString().search(indexStr) == -1) || (showDuplicates)) {
							// myInfo("Search for: NOT FOUND");
							// if record has a valid lat and lon, calc distance to epicenter
							if (!isNaN(parseFloat(name.lat)) &&  !isNaN(parseFloat(name.lon))) {
								name.dist = calcDist(parseFloat(name.lat), parseFloat(name.lon), parseFloat(lati), parseFloat(loni), dsti).toFixed();
											// myInfo("prepEQData: After function calcDist. name.dist=" + name.dist + " unid=" + name.unid + " time=" + name.datetime);
							} 			// (!isNaN(parseFloat(name.lat)) &&  !isNaN(parseFloat(name.lon)))
							// filter earthquakes based on myMaxDist parameter and push them to result set (also take the NO DIST ones)
												// myInfo("prepEQData - myItems.each: Is EQ within range?");
							if ( (parseInt(name.dist, 10) <= parseInt(maxDisti, 10)) || (isNaN(name.dist))) {
												// myInfo("prepEQData - myItems.each: Is EQ within range? = Yes ");
								// if calculated distance is a valid number, add unit
								if (!isNaN(name.dist)){
									switch(dsti) {
										case "M":
											name.distString = Mojo.Format.formatNumber(parseFloat(name.dist)) + " mi";
										break;
										case "N":
											name.distString = Mojo.Format.formatNumber(parseFloat(name.dist)) + " NM";
										break;
										default:
											name.distString = Mojo.Format.formatNumber(parseFloat(name.dist)) + " km";
									} 	// switch(dsti)
								} 		// if (!isNaN(name.dist))
								// else distance cannot be calculated
								else {
									name.distString = $L("NO DIST.");
								} //else
								name.src = pSource;
								name.depthString = Mojo.Format.formatNumber(parseFloat(name.depth), 1) + " km";
								name.flynn_region = name.flynn_region.capitalize();
								name.magString = Mojo.Format.formatNumber(parseFloat(name.mag), 1);
								name.dateTimeHeader = dateTimeHeader;
								name.distHeader = distHeader;
								name.depthHeader = depthHeader;
								myIndex.push(indexStr);
								myNewItems.push(name);
							} // end if
						} // end if (myIndex.toString().search(name.datetime + name.flynn_region) == -1)
					} // end if (parseFloat(name.mag, 10) >= parseFloat(magMin, 10))
				}, myItems); // end function and each
		} // end try
		catch(err){
			Mojo.Controller.getAppController().showBanner({messageText: $L("Data refresh failed!"), icon: "images/small-error-icon.png"},{source: 'notification'});
			myInfo("prepEQData: Data refresh failed! Msg: " + err);
			this.switchSpinnerUSGS("off");
			this.switchSpinnerEMSC("off");
			return 0;
		} // end catch
		// Mojo.Log.info("myIndex = %j", myIndex);
		// Mojo.Log.info("myNewItems = %j", myNewItems);
		// assign the resulting array to the lstEQModel
						// myInfo("prepEQData: listEQModel.items start");
		this.lstEQModel.items = myNewItems;
					// myInfo("prepEQData: listEQModel.items.sort start", mySort1, mySort2);
		if (mySort1 !== "undefined"){
			switch(mySort1) {
				case "datetime":
					this.lstEQModel.items.sort(sort_by(mySort1, mySort2));
					break;
				case "dist":
					this.lstEQModel.items.sort(sort_by(mySort1, mySort2, parseInt));
					break;
				case "mag":
					this.lstEQModel.items.sort(sort_by(mySort1, mySort2, parseFloat));
					break;
				case "flynn_region":
					this.lstEQModel.items.sort(sort_by(mySort1, mySort2));
					break;
				case "dep":
					this.lstEQModel.items.sort(sort_by(mySort1, mySort2, parseFloat));
					break;
				default:
					this.lstEQModel.items.sort(sort_by("datetime", true));
					break;

			} 
		}
					// myInfo("prepEQData: modelChanged start");
		this.controller.modelChanged(this.lstEQModel);
						// myInfo("prepEQData: modelChanged end");
						// myInfo("+++++Retrieved:", myItems.length, "/ loaded:", myNewItems.length, " records from ", pSource);
						// Mojo.Controller.getAppController().showBanner({messageText:"Stop prepEQData" + pSource, icon: "images/small-error-icon.png"},{source: 'notification'});
		nbOfItems = myNewItems.length - prevItems;
						// myInfo("prepEQData: Exiting function", pSource);
		return nbOfItems;
	},
	
	wsEMSCSuccess: function(inSender, inResponse, inRequest) {
		if (inResponse !== undefined) {
			var nbOfItemsEMSC = this.prepEQData(inResponse.unids, "EMSC");
			this.switchSpinnerEMSC("off");
			Mojo.Controller.getAppController().showBanner({messageText: $L("Data loaded from ") + "EMSC" + ": " + nbOfItemsEMSC + " " + $L("items"), icon: "images/day-event-info-press.png"},{source: 'notification'});
			if (nbOfItemsEMSC > 0) {
				this.saveLatestData();
			}
		}
	},
	
	wsEMSCFailure: function(inSender, inError) {
					// myInfo("wsEMSCFAILURE: Start function", inError.status, inError.statusText );
		this.switchSpinnerEMSC("off");
		var str = $L("Request to EMSC web service failed.");
		if (inError.status !== null) {
			str = str + " Status: " + inError.status;
		}
		Mojo.Controller.errorDialog(str);
		this.getLatestData();
					// myInfo("wsEMSCFAILURE: End function");
	},
	
	wsEMSCCancel: function () {
					// myInfo("wsEMSCCANCEL: Start function");
		this.$.wsEMSC.cancel();
		this.switchSpinnerEMSC("off");
					// myInfo("wsEMSCCANCEL: End function");
	},
	
	wsUSGSSuccess: function(inSender, inResponse, inRequest) {
		if (inResponse !== undefined) {
			var myItems = DataGridRenderer.json(CSVParser.parse(inResponse, true).dataGrid, ["orid","unid","version","datetime","lat","lon","mag","depth","NST","flynn_region"], ["string","string","string","string","string","string","string","string","string","string"],"","\n",maxRecords);
			try {
				myItems = JSON.parse(myItems);
				var nbOfItemsUSGS = this.prepEQData(myItems, "USGS");
				this.switchSpinnerUSGS("off");
				Mojo.Controller.getAppController().showBanner({messageText: $L("Data loaded from ") + "USGS" + ": " + nbOfItemsUSGS + " " + $L("items"), icon: "images/day-event-info-press.png"},{source: 'notification'});
				if (nbOfItemsUSGS > 0) {
					this.saveLatestData();
				}
			} // try
			catch(err) {
			} //catch
		}
	},
	
	wsUSGSFailure: function(inSender, inError) {
					// myInfo("wsUSGS-FAILURE: Start function", inError.status, inError.statusText );
		this.switchSpinnerUSGS("off");
		var str = $L("Request to USGS web service failed.");
		if (inError.status !== null) {
			str = str + " Status: " + inError.status;
		}
		Mojo.Controller.errorDialog(str);
		this.getLatestData();
					// myInfo("wsUSGS-FAILURE: End function");
	},
	
	wsUSGSCancel: function () {
					// myInfo("wsUSGS-CANCEL: Start function");
		this.$.wsUSGS.cancel();
		this.switchSpinnerUSGS("off");
					// myInfo("wsUSGSCANCEL: End function");
	},
	
	saveLatestData: function() {
		// save latest displayed data from lstEQModel to a database for use in case of lack of connection
		if (this.lstEQModel){
			db.add("lastData", JSON.stringify(this.lstEQModel),
				function(){
							// myInfo("Saving LastData to dbLastData OK");
				}, 
				function(trans, result){
					Mojo.Log.error("Saving LastData to dbLastData NotOK", result.message);
				}
			);
			var lastUpd = myLastUpdated.toLocaleDateString() + " " + myLastUpdated.toLocaleTimeString();
			db.add("lastUpdated", lastUpd);
		}
	},
	
	getLastDataOK: function(d){
		if (d !== null && d !== undefined) {
			this.lstEQModel = JSON.parse(d);
			this.controller.setWidgetModel('lstEQ', this.lstEQModel);
			this.controller.modelChanged(this.lstEQModel);
			Mojo.Controller.getAppController().showBanner({messageText: $L("Displaying data from last refresh."), icon: "images/day-event-info-press.png"},{source: 'notification'});
						// myInfo("Get LastData from dbLastData OK");
		}
	}, 
	
	getLastDataFailed: function(err) {
		Mojo.Log.error("Get LastData from dbLastData NotOK", err);
	},

	getLatestData: function() {
		this.lstEQModel = {items: [{flynn_region: $L("No data to display")}]};
		this.controller.setWidgetModel('lstEQ', this.lstEQModel);
		this.controller.modelChanged(this.lstEQModel);
		// myInfo("GETLATESTDATA: Start function");
		try {
			// myInfo("GETLATESTDATA: Try to get latest data from DB");
			db.get("lastData", this.getLastDataOK.bind(this), this.getLastDataFailed.bind(this));
		}
		catch(err) {
			// myInfo("GETLATESTDATA: Failed!");
			this.getLastDataFailed(err);
		}
		// myInfo("GETLATESTDATA: End function");
	},
	
	gpsSuccess: function(inSender, inResponse, inRequest) {
					// myInfo("GPSSUCCESS: Start function", JSON.stringify(inResponse));
		if (inResponse !== 'undefined') {
			this.currPrefs.gotGPSfix = true;
			this.currPrefs.lat = inResponse.latitude;
			this.currPrefs.lon = inResponse.longitude;
			if (this.currPrefs.override == 1) {
				var PrefsCookie = new Mojo.Model.Cookie('PrefsCookie');
				try {
					var PrefsData = PrefsCookie.get();
					PrefsData.myLat = inResponse.latitude;
					PrefsData.myLon = inResponse.longitude;
					PrefsCookie.put(PrefsData);
				}
				catch (err) {
					Mojo.Log.error(" ### Could not write preferences cookie with lat/lon of last fix.");
				}
			}
		}
					// myInfo("GPSSUCCESS: End function");
	},
	
	gpsFailure: function(inSender, inError) {
					// myInfo("GPSFAILURE: Start function", JSON.stringify(inError));
		this.currPrefs.gotGPSfix = false;
						// Mojo.Log.info("GPS-Failure. ErrorCode: ", inError.errorCode);
		if (this.currPrefs.lat == 0 && this.currPrefs.lon == 0) {
						// Show alert dialog allowing user to either enter his location in the Prefs or open Location Svc. to switch GPS on.
						// myInfo("GPSFAILURE: lat and lon = 0, no GPS fix, showing alert");
			var myChoices = [];
			if (this.currPrefs.triedGPSalready == false ) {
				myChoices.push({label:$L('Retry to get a fix'), value:'Retry', type:'affirmative'});
							// myInfo("GPSFAILURE: showing alert the first time");
			}
			else {
				myChoices.push({label:$L('Retry to get a fix'), value:'Retry', type:'secondary'});
							// myInfo("GPSFAILURE: showing alert the second+ time");
			}
			myChoices.push({label:$L('Open Location Services'), value:'LocSvc', type:'affirmative'});
			myChoices.push({label:$L('Open Preferences'), value:'Prefs', type:'affirmative'});
			this.controller.showAlertDialog({
				preventCancel: false,
				onChoose: function(value) {
					if (value == 'Prefs') {
						this.controller.stageController.pushScene("scnPrefs");
					}
					if (value == 'LocSvc') {
						this.controller.serviceRequest('palm://com.palm.applicationManager', {
							method: 'launch',
							parameters:  {
								id: 'com.palm.app.location',
								params: {}
							}
						});
					}
					if (value == 'Retry') {
						this.currPrefs.triedGPSalready = true;
						this.$.gps.getCurrentPosition();
					}
					if (value == 'undefined') {
					}
				},
				title: $L("Your location is unknown!"),
				message: $L({value: "Cannot calculate distance without knowing your current location. Either switch on GPS/Location Services or enter your coordinates in the preferences screen. Note: After switching GPS on it may take several minutes until your location can be fixed.", key: "noMyLoc"}),
				choices: myChoices
			});
		}
		// myInfo("GPSFAILURE: End function");
	},
	
	switchSpinnerUSGS: function(state) {
					// myInfo("switchSPINNERUSGS: Start function");
		if (state.toUpperCase() == "ON") {
					// myInfo("switchSPINNERUSGS: ON");
			this.hdrSpinnerModel.spinning = true;
		}
		else {
					// myInfo("switchSPINNERUSGS: OFF");
			this.hdrSpinnerModel.spinning = false;
		}
		this.controller.modelChanged(this.hdrSpinnerModel);
					// myInfo("switchSPINNERUSGS: End function");
	},
	
	switchSpinnerEMSC: function(state) {
					// myInfo("switchSpinnerEMSC: Start function");
		if (state.toUpperCase() == "ON") {
					// myInfo("switchSpinnerEMSC: ON");
			this.hdrSpinnerModelEMSC.spinning = true;
		}
		else {
					// myInfo("switchSpinnerEMSC: OFF");
			this.hdrSpinnerModelEMSC.spinning = false;
		}
		this.controller.modelChanged(this.hdrSpinnerModelEMSC);
					// myInfo("switchSpinnerEMSC: End function");
	},
	
	lstEQItemrendered: function(inSender, inListElement, inItemModel, inItemNode) {
		if ((parseFloat(inItemModel.mag) > 5) && (parseFloat(inItemModel.mag) <= 6)) {inItemNode.getElementsByClassName('label')[0].style.color = 'orange';}
		if ((parseFloat(inItemModel.mag) > 6) && (parseFloat(inItemModel.mag) <= 7)) {inItemNode.getElementsByClassName('label')[0].style.color = 'red';}
		if  (parseFloat(inItemModel.mag) > 7) {
			inItemNode.getElementsByClassName('label')[0].style.color = 'red';
			inItemNode.getElementsByClassName('label')[0].style.background = 'yellow';
		}
	},
	
	picMapTopTenTap: function(inSender, event) {
		var argForPushing = this.lstEQModel.items.slice(0,10);
		this.controller.stageController.pushScene("scnMapTopTen", argForPushing, this.currPrefs.tecPlates);
	},
	
	lstEQListtap: function(inSender, event) {
		var argForPushing = [event.item];
		this.controller.stageController.pushScene("scnMapTopTen", argForPushing, this.currPrefs.tecPlates);
	}
};